<!-- PaginationComponent.vue -->
<template>
  <div class="pagination-container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :small="false"
      :disabled="false"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalItems"
      @size-change="handlePageSizeChange"
      @current-change="handlePageChange"
      :prev-text="$t('previousPage')"
      :next-text="$t('nextPage')"
    />
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElNotification } from 'element-plus'
import Task from '../apis/Task'

const { t } = useI18n()

const props = defineProps({
  totalItems: {
    type: Number,
    default: 0
  },
  itemsPerPage: {
    type: Number,
    default: 10
  },
  currentPage: {
    type: Number,
    default: 1
  }
})

const emit = defineEmits(['dataChange', 'currentChange', 'sizeChange'])

const currentPage = ref(props.currentPage)
const pageSize = ref(props.itemsPerPage)

watch(() => props.currentPage, (newVal) => {
  currentPage.value = newVal
})

watch(() => props.itemsPerPage, (newVal) => {
  pageSize.value = newVal
})

const fetchData = async (page, size) => {
  try {
    const response = await Task.getTaskSelect({
      currentPage: page,
      pageSize: size,
    })
    if (response.data == null) {
      throw new Error(t('noMatchingData'))
    }
    emit('dataChange', {
      tableData: response.data,
      totalItems: response.total,
    })
  } catch (error) {
    ElNotification({
      title: t('error'),
      message: error.message,
      type: 'error',
    })
  }
}

const handlePageChange = (page) => {
  emit('currentChange', page)
  fetchData(page, pageSize.value)
}

const handlePageSizeChange = (size) => {
  emit('sizeChange', size)
  fetchData(currentPage.value, size)
}
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
